package com.atguigu.gmall_logger.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.Constansts;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Smexy on 2021/6/30
 */
@RestController
@Slf4j  // 作用  自动帮你创建  Logger log = Logger.getLogger(LogController.class);
//@Log4j   也可以
public class LogController {

    //Logger logger = Logger.getLogger(LogController.class);

    @Autowired
    private KafkaTemplate<String,String> producer;


    /*
            value的值需要和gmall_mock中LogUploader的url对应

            形参的属性名需要和gmall_mock中LogUploader的请求参数名一致



            {"area":"guangdong","uid":"64","itemid":25,"npgid":42,"evid":"addCart","os":"ios","pgid":28,"appid":"gmall2019","mid":"mid_343","type":"event"}
            少了时间，没有时间的数据是没有分析意义的！
     */
    @RequestMapping(value = "/log")
    public String handleLog(String logString){


        //在服务器端为日志生成时间
        JSONObject jsonObject = JSON.parseObject(logString);

        jsonObject.put("ts",System.currentTimeMillis());

        //将日志数据落盘，使用Log4j

        //System.out.println(logString);

        log.info(jsonObject.toString());

        //将数据生产到kafka
        if ("event".equals(jsonObject.getString("type"))){

            producer.send(Constansts.GMALL_EVENT_LOG,jsonObject.toString());

        }else {

            producer.send(Constansts.GMALL_STARTUP_LOG,jsonObject.toString());
        }

        return "success";

    }

}
